<template>
    <base-breadcrumb :title="$route.meta.title">
        <!-- BIM培训台账 -->
        <div id="base-breadcrumb" style="position: relative; overflow: hidden">
            <!-- 搜索 -->
            <searchData :searchData="searchArr" @search="search"></searchData>
            <!-- 表格 -->
            <a-card :bordered="false">
                <!-- <title-name :title="$route.meta.title"></title-name> -->
                <!-- 表格 -->
                <list-table
                        ref="table"
                        :pageKeys="['pageNum', 'pageSize', 'total']"
                        :columns="columns"
                        :startIndex="0"
                        :filterData="filterData"
                        :request="loadData"
                        :statistics-config="{
            use: true, //是否统计，传false不会显示操作栏
            temp: statistics
          }"
                        :exportPermission="{ select: 'BIM_005_exp_05', all: 'BIM_005_exp_05' }"
                        :exportConfig="{ use: true, select: $route.meta.title, all: $route.meta.title }"
                >
                    <!-- 新增 -->
                    <a-button
                            v-btnPermission="'BIM_005_add_01'"
                            slot="prefix"
                            class="mb12"
                            icon="plus"
                            type="primary"
                            @click="handleManage(2)"
                    >新增</a-button
                    >
                    <!-- 下载附件 -->
                    <template slot="suffix" slot-scope="scoped">
                        <a-button
                                v-btnPermission="'BIM_005_dow_06'"
                                :loading="downLoading"
                                class="mb12"
                                icon="cloud-download"
                                :disabled="scoped.selectedRowKeys && scoped.selectedRowKeys.length === 0"
                                type="primary"
                                @click="downZip(scoped.selectedRowsMap)"
                        >批量下载附件</a-button
                        >
                        <ExportExcel
                                ref="exportExcel"
                                :export-list="exportList"
                                icon="export"
                                :file-name="$route.meta.title + '模板.xlsx'"
                                button-text="下载导入模板"
                                :beforeDownload="beforeDownload"
                        />
                        <ExcelImportButton
                                ref="excelImportButton"
                                :loading="loadingImport"
                                icon="import"
                                button-text="批量导入"
                                @handleSubmit="handleImport"
                                v-if="hideBuquBtn()"
                        />
                    </template>
                    <template slot="actions" slot-scope="text, record">
                        <template>
                            <a @click="handleManage(0, record)">查看</a>
                            <a-divider type="vertical"></a-divider>
                            <a  v-selfBtn2="{code: 'CODCYWJL',id:record.creatorId}" @click="handleManage(1, record)">编辑</a>
                            <a-divider v-selfBtn2="{code: 'CODCYWJL',id:record.creatorId}" type="vertical"></a-divider>
                            <a v-selfBtn2="{code: 'CODCYWJL',id:record.creatorId}" class="del_btn" @click="handleRemove(record.id, search)">删除</a>
                        </template>
                    </template>
                </list-table>
            </a-card>
        </div>
        <!-- 查看附件 -->
        <DialogForm ref="dialogForm" :visible.sync="visible" edit-model="V" :width="1000" :fileList="fileList" />
        <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%" />
    </base-breadcrumb>
</template>

<script>
  import {
    getPageBimTrainLedger,
    deleteBimTrain,
    getBimTrainLedgerSummary,
    insertBimTrainBatch,
    getPageTypesLabel
  } from '@/api/bimIntegrate/bimResource.js'
  import BasePage from '@/views/basePage'
  import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
  import DialogForm from '@/components/DialogForm' // 弹窗
  import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
  import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
  import Selector from '@/components/Select/Selector'
  import OrgTreeSelect from '@/components/OrgTreeSelect'

  const searchArr = [
    // 搜索框
    {
      name: '举办单位',
      valueKey: 'organizerId',
      type: SelectCompanyAndProject,
      extraParams: {
        notContainTags: ['PD']
      }
    },
    {
      name: '培训形式',
      type: 'select',
      value: 'category',
      data: [
        {
          label: '现场',
          value: 0
        },
        {
          label: '线上',
          value: 1
        },
        {
          label:'现场+线上',
          value:2
        }
      ]
    },
    {
      name: '培训分类',
      valueKey: 'trainContentId',
      type: Selector,
      customApi: getPageTypesLabel,
      customQuery: { param: { type: '39' } },
      dataValue: 'data.list'
    },
    {
      name: '培训时间',
      type: 'dateRange',
      value: 'trainTime',
      attr: {
        rangeFormat: ['startTime', 'endTime']
      }
    },
    {
      name: '培训名称',
      type: 'input',
      value: 'trainName'
    },
    {
      name: '授课人',
      type: 'input',
      value: 'lecturer'
    }
  ]
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      isHidden: true,
      width: 80,
      customRender() {
        return Number(arguments[2]) + 1
      }
    },
    {
      title: '举办单位',
      ellipsis: true,
      dataIndex: 'organizer'
    },
    {
      title: '培训分类',
      ellipsis: true,
      dataIndex: 'trainContent'
    },
    {
      title:'培训名称',
      ellipsis: true,
      dataIndex: 'trainName'
    },
    {
      title: '参培人数',
      ellipsis: true,
      dataIndex: 'numberOfPeople',
      minWidth: '80px',
    },
    {
      title: '授课人',
      ellipsis: true,
      dataIndex: 'lecturer'
    },
    {
      title: '培训地点',
      ellipsis: true,
      dataIndex: 'placeForTraining'
    },
    {
      title: '培训时间',
      ellipsis: true,
      width: 190,
      dataIndex: 'trainTime',
      customRender() {
        return arguments[1].startDate && arguments[1].endDate ? arguments[1].startDate + '~' + arguments[1].endDate : '无'
      },
      excelConfig: {
        note: '日期格式：XXXX年XX月XX日-XXXX年XX月XX日；如：2020年10月1日-2020年10月4日'
      }
    },
    {
      title: '人均学时',
      ellipsis: true,
      dataIndex: 'averageClasshours',
      minWidth: '80px',
    },
    {
      title: '期数',
      ellipsis: true,
      dataIndex: 'periodsNumber'
    },
    {
      title: '费用',
      ellipsis: true,
      dataIndex: 'trainExpenses'
    },
    {
      title: '培训形式',
      ellipsis: true,
      dataIndex: 'categoryName',
      excelConfig: {
        dataValidation: {
          type: 'list'
        }
      },
      options: ['现场', '线上','现场+线上']
    },
    {
      title: '操作',
      dataIndex: 'actions',
      width: '230px',
      isHidden: true,
      align: 'center',
      fixed: 'right',
      scopedSlots: { customRender: 'actions' }
    }
  ]


  export default {
    name: 'a' + Date.now(),
    extends: new BasePage(),
    components: {
      DialogForm,
      ExportResult,
      ExportExcel
    },
    data() {
      this.columns = columns
      this.searchArr = searchArr
      return {
        queryParam: {}, // 查询参数
        removeApi: { remove: deleteBimTrain }, // 删除台账
        visible: false, // 查看附件弹窗控件
        visibleExport: false, // 导入结果弹窗控件
        exportList: [{ columns: [], datas: [] }], // 导入配置项
        fileList: [], // 当前文件列表
        loadingImport: false, // 导入loading
        countInfo: {}, // 汇总数据
        countList: [
          {
            list: [
              {
                title: '总人数：',
                value: 'infoPeople',
                unit: '人'
              }
            ]
          },
          {
            list: [
              {
                title: '期数：',
                value: 'bimTotal',
                unit: '期'
              }
            ]
          },
          {
            list:[
              {
                title:'费用：',
                value:'bimCost',
                unit:'元'
              }
            ]
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: (parameter) => {
          this.getSummary()
          const requestParameters = Object.assign({}, parameter, { param: this.queryParam })
          return getPageBimTrainLedger(requestParameters).then((res) => {
            if (res.code === '0') {
              return { code: 200, data: res.data?.list, total: res.data?.total }
            }
          })
        },
        importCheck: {
          举办单位: 'organizer',
          培训分类: 'trainContent',
          培训名称: 'trainName',
          参培人数: 'numberOfPeople',
          授课人: 'lecturer',
          培训地点: 'placeForTraining',
          培训时间: 'trainTime',
          人均学时: 'averageClasshours',
          期数: 'periodsNumber',
          费用: 'trainExpenses',
          培训形式: 'categoryName'
        } // 导入字段对应
      }
    },
    methods: {
      /**
       * @description: 导出模板前的回调处理
       * @param {Promise} callback：导出方法
       */
      async beforeDownload() {
        let columnsExport = this.$clone(this.columns)
        // 若培训内容枚举值不存在，则添加培训内容的枚举值
        // if (!columnsExport[3].options) {
        //   this.loadingExport = true
        //   const res = await getPageTypesLabel({ param: { type: '39' } }).catch(() => {
        //     this.loadingExport = false
        //   })
        //   if (res?.code === '0') {
        //     // 添加培训内容枚举
        //     columnsExport[3].options = res.data?.list?.map((item) => item.name)
        //   }
        // }
        // 设置默认导出配置项
        this.exportList = [
          {
            columns: columnsExport,
            datas: [{}]
          }
        ]
      },
      /**
       * @description: 批量导入
       * @param {Array} data：导入列表
       */
      async handleImport(e) {
        let form = []
        // 遍历校验表格字段，且添加表单
        for (let index in e) {
          form.push({})
          let keys = e[index]
          let listItem = form[index]
          // 校验excel的表头字段
          for (let i in this.importCheck) {
            let item = this.importCheck[i]
            if (!Object.keys(keys).includes(i) && item !== 'remark') {
              this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
              return
            } else {
              // 培训类别格式化
              if (item === 'categoryName') {
                listItem[item] = keys[i]
                listItem['category'] = { '现场': 0, '线上': 1, '现场+线上' :2 }[keys[i]]
              } else if (
                (item === 'numberOfPeople' || item === 'averageClasshours' || item === 'periodsNumber' || item === 'trainExpenses') &&
                typeof keys[i] !== 'number'
              ) {
                this.$message.warning(`第${Number(index) + 1}行${i}必须为数字`)
                return
              }else if (item === 'trainTime') {
                let trainTime = keys[i]?.split('-')
                let isDate = /年|月|日/g
                let formatDate = (e) => {
                  return e?.replace(/年|月/g, '-')?.replace(/日/g, '')
                }
                if (trainTime.length === 2 && isDate.test(trainTime[0]) && isDate.test(trainTime[1])) {
                  // 添加培训开始时间
                  listItem.startDate = formatDate(trainTime[0])
                  // 添加培训结束时间
                  listItem.endDate = formatDate(trainTime[1])
                } else {
                  this.$message.warning(
                    `第${Number(index) + 1}行${i}格式不正确，请填写成类似如"2020年10月1日-2020年10月4日"格式`
                  )
                  return
                }
              } else {
                listItem[item] = keys[i]
              }
            }
          }
        }
        // 开始导入
        this.loadingImport = true
        const importRes = await insertBimTrainBatch(form).catch(() => {
          this.loadingImport = false
        })
        this.loadingImport = false
        // 导入成功
        if (importRes?.code === '0') {
          if (importRes.data?.list?.length > 0) {
            // 配置导出项，且打开导出结果
            let columnsExport = this.$clone(this.columns)?.filter((i) => i.header !== '操作' && !i.isHidden)
            // 若培训内容枚举值不存在，则添加培训内容的枚举值
            if (!columnsExport[2].options) {
              this.loadingImport = true
              const ress = await getPageTypesLabel({ param: { type: '39' } }).catch(() => {
                this.loadingImport = false
              })
              this.loadingImport = false
              // 添加下拉枚举值
              if (ress?.code === '0') {
                // 添加培训内容枚举
                columnsExport[2].options = ress.data?.list?.map((item) => item.name)
              }
            }
            // 表头添加失败原因
            columnsExport.push({
              dataIndex: 'failureReason',
              ellipsis: true,
              title: '失败原因'
            })

            this.exportList = [
              {
                successCount: importRes.data.successCount,
                columns: columnsExport,
                datas: importRes.data.list
              }
            ]
            this.visibleExport = true
          } else {
            this.$message.success('导入成功')
          }
          // 如果有导入成功条数，则刷新表格
          importRes.data?.successCount > 0 && this.search()
        }
      },
      /**
       * 汇总请求
       */
      getSummary() {
        getBimTrainLedgerSummary({ param: this.queryParam }).then((res) => {
          if (res.code === '0') {
            this.countInfo = res.data
          }
        })
      },
      /**
       * 汇总
       */
      statistics() {
        return this.countList.map((item, index) => (
          <span key={index}>
          {item.list.map((i, idx) => (
              <span key={idx}>
            {i.title}
            <a>
            <b>{this.countInfo?.[i.value]  + i.unit } </b>
            </a>
        {idx % 2 === 0 ? '，' : ''}
      </span>
      ))}
      </span>
      ))
      },
      /**
       * 格式化数据
       */
      filterData(datas) {
        let list = this.$clone(datas)
        list.forEach((item, index) => {
          item.index = index + 1
          item.category = ['现场', '线上','现场+线上'][item.category]
          item.trainTime = item.startDate && item.endDate ? item.startDate + '~' + item.endDate : '无'
        })
        return list
      },
      /**
       * 搜索
       */
      search(value) {
        value && (this.queryParam = value)
        this.$refs.table.getData(null, true)
      },
      /**
       * 操作栏
       */
      handleManage(type, record) {
        this.editModel = type
        let query = {
          editModel: type
        }
        if (record && record.id) {
          query.id = record.id
        }
        this.$router.push({
          name: '/bimResource/trainingEdit',
          query
        })
      }
    }
  }
</script>
